<?php

namespace App\Http\Controllers\Dingtalk;

use App\Http\Controllers\Controller;


class DingtalkController extends Controller
{

    private $CorpID = "ding6877aa5d92aac51035c2f4657eb6378f";
    private $CorpSecret = "OUaNHxKHJJZ6sWEHpbDWXLiUGCoNgFM3Q94m23iw9kMY8rSBlBeZ-TMQaV_9SwOp";
    private $AgentID = "79357881";
    public $accessToken;

    function __construct() {
        $this->accessToken = $this->getToken();
    }

    public function curl($url, $data = NULL){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if(!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        /*curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json')
        );*/
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    // 获取接口凭证
    public function getToken() {
        $url = "https://oapi.dingtalk.com/gettoken?corpid=" . $this->CorpID . "&corpsecret=" . $this->CorpSecret;
        $AccessToken = $this->curl($url);
        $AccessToken = json_decode($AccessToken);
        $token = $AccessToken->access_token;
        return $token;
    }

    public function getUsers() {
        // 获取部门
        $users = null; // 返回部门数组
        $url = "https://oapi.dingtalk.com/department/list?access_token=" . $this->getToken();
        $departments = json_decode($this->curl($url), true);
        $arr_d = $departments['department'];
        foreach($arr_d as $k=>$v) {
            //echo $v['name'] . "(" . $v['id'] . ")<br>";
            // 获取部门成员
            $url = "https://oapi.dingtalk.com/user/simplelist?access_token=" . $this->getToken() . "&department_id=" . $v['id'];
            $arr_u = json_decode($this->curl($url), true);
            $arr_s = null;
            if(!$arr_u['userlist'] == []) {
                for($i=0; $i<sizeof($arr_u['userlist']); $i++) {
                    $arr_s[] = [
                        'user_id' => $arr_u['userlist'][$i]['userid'],
                        'user_name' => $arr_u['userlist'][$i]['name'],
                    ];
                }
                $users[] = [
                    'user_department' => $v['name'],
                    'user_detail' => $arr_s
                ];
            }
        }

        return $users;

    }

}
